package com.itheima.d3_tcp.no3;

import org.apache.commons.io.IOUtils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 案例：使用TCP通信方式实现文件的上传（使用线程池优化）
 */
public class ServerDemo03B {
    public static void main(String[] args) throws IOException {
        System.out.println("---------服务端启动了（使用线程池优化）-----------");

        //创建线程池对象
        ThreadPoolExecutor pool = new ThreadPoolExecutor(3, 5,
                2, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(8),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());

        //1 创建SocketServer对象，注册端口
        ServerSocket ss = new ServerSocket(8888);

        while (true) {
            //2 接收客户端的连接，得到客户端的Socket对象
            Socket socket = ss.accept();  //循环接收客户端的连接

            //开启一个线程处理任务
            pool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        //3 通过Socket获取字节输入流对象，创建FileOutputStream字节输出流对象
                        InputStream is = socket.getInputStream();
                        FileOutputStream os = new FileOutputStream("d:/2.jpg");
                        //4 将输入流中的内容通过输出流写到硬盘中
                        IOUtils.copy(is, os);
                        System.out.println("上传成功~");
                        //5 释放资源
                        os.close();
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}
